package edu.upb.acs.jobsmaps;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * Created by dani on 5/18/2014.
 */
public class AddressLookup {

	private final String TAG = AddressLookup.class.getName();

	private final double longitude;
	private final double latitude;
	private final Context context;

	public AddressLookup(double latitude, double longitude, Context context) {
		this.latitude = latitude;
		this.longitude = longitude;
		this.context = context;
	}

	public String getAddress() {
		int maxResults = 1;

		StringBuilder addressLocation = new StringBuilder();

		Geocoder geocoder = new Geocoder(context, Locale.getDefault());
		List<Address> foundAddresses = null;

		if (!geocoder.isPresent()) {
			Log.d(TAG, "Geocoder is not available");
			return "";
		}

		Log.d(TAG, "Geocoder is available. Get address..");

		try {
			foundAddresses = geocoder.getFromLocation(latitude, longitude, maxResults);
			Log.d(TAG, "Got " + foundAddresses.size() + " addresses");
			if (foundAddresses.size() == 0) {
				return "No address found";
			}

			for (int i = 0; i < foundAddresses.size(); i++) {
				Address foundAddress = foundAddresses.get(i);
				if (foundAddress.getThoroughfare() != null && foundAddress.getThoroughfare().length() > 0) {
					addressLocation.append(foundAddress.getThoroughfare());
					addressLocation.append(",");
					addressLocation.append(foundAddress.getLocality());
				} else {
					for (int j = 0; j <= foundAddress.getMaxAddressLineIndex(); j++) {
						addressLocation.append(foundAddress.getAddressLine(j));
						addressLocation.append(", ");
						Log.d(TAG, "Address = " + foundAddress.getAddressLine(j));
					}
					addressLocation.replace(addressLocation.length() - 2, addressLocation.length() - 1, "");
				}

				Log.d(TAG, "Found address" + foundAddresses.get(i));
				Log.d(TAG, "Display address" + addressLocation);

			}
		} catch (IOException e) {
			Log.e(TAG, "Can not get address", e);
		}
		return addressLocation.toString();

	}
}
